<template>
  <div>
    <UploadFileTable ref="uploadFileRef" :formList="formList" @uploadFile="uploadFile"/>
    <a-descriptions :title="$t('all.autotext148')"></a-descriptions>
    <a-table
      bordered
      :data-source="formList"
      :pagination="false"
      size="small"
      :rowKey="record => record.uniqueId"
    >
      <a-table-column
        :title="$t('all.autotext240')"
        key="No"
        data-index="No"
        style="width: 3%"
      />
      <a-table-column
        v-if="type===2"
        :title="$t('all.autotext1049')"
        key="visitRecordId"
        data-index="visitRecordId"
        width="200px"
      >
        <template slot-scope="text, record">
          <a-select
            style="margin: -5px 0; width: 100%"
            :placeholder="$t('all.autotext1348')"
            v-if="record.editable"
            v-model="record.visitRecordId"
            @change="(e, node) => handleVisitChange(e, node, record)"
          >
            <a-select-option
              v-for="item in stages"
              :key="item.id"
              :value="item.id"
              :name="item.name"
              :stage="item.stage"
            >
              <span>{{ item.name }}:{{ item.stage }}</span>
            </a-select-option>
          </a-select>
          <template v-else>{{ record.visitRecordInfo }}</template>
        </template>
      </a-table-column>
      <a-table-column
        :title="$t('all.autotext1278')"
        key="applyType"
        data-index="applyType"
        width="260px"
      >
        <template slot-scope="text, record, index">
          <a-select
            style="margin: -5px 0; width: 100%"
            key="applyType"
            v-model="record.applyType"
            :placeholder="$t('all.autotext1348')"
            v-if="record.editable"
            @change="(e) => applyTypeChange(e, record, index)"
          >
            <a-select-option v-for="item in (record.feeList || mattersList)" :key="item.id" :value="item.applyType">
              {{ item.applyType }}
            </a-select-option>
          </a-select>
          <template v-else>
            {{ record.applyType }}
          </template>
        </template>
      </a-table-column>
      <a-table-column
        v-if="type===2"
        :title="$t('all.autotext850')"
        key="happenDate"
        data-index="happenDate"
      >
        <template slot-scope="text, record">
          <a-date-picker
            v-model="record.happenDate"
            :disabled="record.defaulted"
            valueFormat="YYYY-MM-DD"
            v-if="record.editable"
          />
          <template v-else>
            <span v-if="text">{{ text | moment('YYYY-MM-DD') }}</span>
            <span v-else>-</span>
          </template>
        </template>
      </a-table-column>
      <a-table-column :title="$t('all.autotext1256')" key="amount" data-index="amount">
        <template slot-scope="text, record">
          <template v-if="record.editable">
            <a-tooltip :visible="isAmountValid(record)" :overlayStyle="{minWidth:'280px'}">
              <template slot="title">
                <span v-if="record.costMin && record.costMax">{{ $t('all.autotext1266') }}：{{ record.costMin }}~{{ record.costMax }}，{{ $t('all.autotext801') }}</span>
                <span v-else-if="record.costMin">{{ $t('all.autotext1266') }}：{{ $t('all.autotext495') }}{{ record.costMin }}，{{ $t('all.autotext801') }}</span>
                <span v-else-if="record.costMax">{{ $t('all.autotext1266') }}：0~{{ record.costMax }}，{{ $t('all.autotext801') }}</span>
              </template>
              <a-input
                style="margin: -5px 0; width: 100%"
                key="amount"
                type="number"
                :precision="2"
                :max="999999999.99"
                :min="0"
                v-model="record.amount"
                :placeholder="$t('all.autotext1527')"
                @input="e=>onAmountChange(record,e)"
                :style="{borderColor: isAmountValid(record) ? '#f5222d' : ''}"
              />
            </a-tooltip>
          </template>

          <template v-else>
            {{ text }}
          </template>
        </template>
      </a-table-column>
      <a-table-column
        :title="$t('all.autotext1103')"
        key="upload"
        data-index="upload"
        style="width: 20%"
      >
        <template slot-scope="text, record, index">
          <div v-if="record.apv == 1">
            <!-- <a-button v-if="record.editable" @click="uploadFile(record, index)" :disabled="record.btnSwitch">{{ $t('all.autotext565') }}</a-button> -->
            <a-select
              v-if="record.editable"
              v-model="record.files"
              mode="multiple"
              :maxTagCount="1"
              style="width: 100%; max-width: 300px;"
              @change="fileChange($event, record, index)"
            >
              <a-select-option v-for="(item, i) in correctFileList" :key="i" :value="item.fileUrl">
                <span :title="item.fileName">{{ item.fileName }}</span>
              </a-select-option>
            </a-select>
            <div v-else>
              <!-- epv1.5：查看脱敏后的文件-->
              <ViewFile v-if="record.fileList.length" :data="getFileList(record)">
                <a>{{ $t('all.autotext568') }}</a>
              </ViewFile>
              <span v-else>{{ $t('all.autotext263') }}</span>
            </div>
          </div>
          <div v-else>
            <span style="color: #999;">{{ $t('all.autotext263') }}</span>
          </div>
        </template>
      </a-table-column>
      <a-table-column
        v-if="type===1"
        :title="$t('all.autotext1027')"
        key="supplyRemark"
        data-index="supplyRemark"
        style="width: 20%"
      >
        <template slot-scope="text, record">
          <div v-if="record.apv == 1">
            <a-checkbox
              @change="e=>onChange1(record, e)"
              v-if="record.editable"
              style="margin-right: 5px"
              :checked="record.supply == 1"
            ></a-checkbox>
            <a-input
              style="margin: -5px 0; width:90%"
              key="supplyRemark"
              v-model="record.supplyRemark"
              :placeholder="$t('all.autotext486')"
              v-if="record.editable"
              :disabled="!record.btnRemarks"
            />
            <div v-else>
              {{ record.supplyRemark !== '' ? record.supplyRemark : $t('all.autotext263') }}
            </div>
          </div>
          <div v-else>
            <span style="color: #999">{{ $t('all.autotext263') }}</span>
          </div>
        </template>
      </a-table-column>
      <!-- <a-table-column :title="$t('all.autotext1709')" key="comment" data-index="comment">
        <template slot-scope="text">
          <span v-if="text">{{ text }}</span>
        </template>
      </a-table-column> -->
      <a-table-column :title="$t('all.autotext187')">
        <template slot-scope="text, record">
          <div v-if="record.editable">
            <span v-if="record.isNew">
              <a @click="saveRow(record)">{{ $t('all.autotext176') }}</a>
              <a-divider type="vertical" />
              <a-popconfirm :title="$t('all.autotext718')" @confirm="remove(record)">
                <a>{{ $t('all.autotext379') }}</a>
              </a-popconfirm>
            </span>
            <span v-else>
              <a @click="saveRow(record)">{{ $t('all.autotext321') }}</a>
              <a-divider type="vertical" />
              <a @click="cancel(record)">{{ $t('all.autotext975') }}</a>
            </span>
          </div>
          <span v-else>
            <a @click="toggle(record)">{{ $t('all.autotext919') }}</a>
            <a-divider type="vertical" />
            <a-popconfirm :title="$t('all.autotext718')" @confirm="remove(record)">
              <a>{{ $t('all.autotext379') }}</a>
            </a-popconfirm>
          </span>
        </template>
      </a-table-column>
    </a-table>
    <a-button
      style="width: 100%; margin-top: 16px; margin-bottom: 8px"
      type="dashed"
      icon="plus"
      @click="newMember"
    >
      {{ $t('all.autotext409') }}
    </a-button>
    <!-- <UploadFile
      :uploadFileVisible="uploadFileVisible"
      :currentTarget="currentTarget"
      @closeUpload="closeUpload"
      ref="uploadFileRef"
    /> -->
    <a-modal v-model="commentVisible" :title="$t('all.autotext1566')" @ok="handleOk">
      <h3>{{ $t('all.autotext1567') }}</h3>
      <a-form-model
        ref="ruleForm"
        layout="vertical"
        :model="form"
        :rules="rules"
      >
        <a-form-model-item :label="$t('all.autotext1709')" prop="comment">
          <a-textarea
            v-model="form.comment"
            :placeholder="$t('all.autotext1569')"
            :maxLength="50"
            :auto-size="{ minRows: 3, maxRows: 5 }"
          />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import moment from 'moment'
import ViewFile from './researcher/ViewFile'
// import UploadFile from './UploadFile'
import UploadFileTable from './UploadFileTable'
import { visitStageByFeeCategory, getAllFeeCategory } from '@/api/overview/visit'

export default {
  props: {
    type: {
      type: Number,
      required: true
    },
    researchId: [String, Number],
    researchDetailId: [String, Number],
    ptsId: [String, Number],
    ptsTypeId: [String, Number],
    versionId: [String, Number], // 访视阶段
    stages: Array, // 访视阶段
    mattersList: Array, // 报销类目列表
    mattersItem: Array // 报销类目列表
  },
  components: { ViewFile, UploadFileTable },
  data () {
    return {
      totalAmt: 0,
      formList: [],
      loading: true,
      uploadFileVisible: false,
      currentTarget: {},
      saveTarget: '',
      commentVisible: false,
      form: {
        comment: ''
      },
      rules: {
        comment: [{ required: true, message: this.$t('all.autotext1570'), trigger: 'blur' }]
      },
      fileList: []
    }
  },
  computed: {
    correctFileList () {
      return this.fileList.filter(item => ![0, 2, 4, 6].includes(item.fileStatus))
    }
  },
  watch: {
    mattersItem (newVal) {
      this.fillBackDatackData(newVal)
    },
    immediate: true
  },
  methods: {
    backFileList (val) {
      this.fileList = val
      this.$refs.uploadFileRef.backFileList(val)
    },
    async fillBackDatackData (items) {
      const typeAll = await getAllFeeCategory({
        proId: localStorage.getItem('CURRENT_PROID'),
        type: this.type,
        ptsTypeId: this.ptsTypeId
      })
      let cacheFormList = []
      items && items.map((item) => {
        cacheFormList.push({
          No: cacheFormList.length + 1, // No
          uniqueId: Math.random().toString().substr(2, 10), // 当前行的唯一标识
          isNew: true,
          apv: this.type === 2 ? 1 : null, // 是否审批
          supplyRemark: '', // 补充说明
          editable: false, // 可修改
          manageCostId: item.proFlowFeeCategoryId, // 报销类目id (费用科目接口返回的id)
          supply: 0, // 是否研究者/受试者补充资料  0:否  1:是   费用科目接口返回的apv字段决定，apv=1时开启图片上传功能
          btnSwitch: false, // 上传和补充资料二选一
          afterFileUrl: '', // 脱敏后资料地址
          fileName: [], // 资料名字
          // fileList: [{ fileUrl: item.fileUrl, fileName: '121' }], // TODO
          // fileList: item.fileUrl?.split(',').map(i => {
          //   return { fileName: i, fileUrl: i.split('/payment/')[1] }
          // }),
          defaultAmt: null, // 默认金额
          loading: false,
          // 受试者
          ...item,
          btnRemarks: item.supply === 1, // 上传和补充资料二选一
          files: item.fileUrl.split(','),
          visitRecordId: this.type === 2 && this.checkDataExistsInList(item.visitRecordId, this.stages, 'id') ? item.visitRecordId : '', // 访视记录id 访视版本下的访视记录列表id
          visitRecordInfo: this.type === 2 && this.checkDataExistsInList(item.visitRecordId, this.stages, 'id') ? this.fillStages(this.stages, item.visitRecordId) : '', // 访视名词  访视列表返回的name
          ...this.fillApplyType(typeAll, item)
        })
      })
      this.formList = cacheFormList
      this.calculateCost()
      this.$emit('updateFee', this.formList, this.totalAmt, this.fileList)
    },
    // 访视阶段名称变更回显判断
    fillStages (stages, visitRecordId) {
      let filter = stages.find(item => item.id === visitRecordId)
      return `${filter.name}:${filter.stage}`
    },
    fillApplyType (typeAll, item) {
      if (this.type === 2 && !this.checkDataExistsInList(item.visitRecordId, this.stages, 'id')) {
        return {
          applyType: null, // 报销类目
          happenDate: '', // 发生日期
          amount: 0, // 申请金额
          fileList: [],
          files: []
        }
      } else if (!this.checkDataExistsInList(item.proFlowFeeCategoryId, typeAll, 'id')) {
        if (this.checkDataExistsInList(item.applyType, typeAll, 'applyType') && (this.type === 2 ? this.checkInList(item, typeAll) : true)) {
          let obj = typeAll.filter(v => v.applyType === item.applyType)[0]
          return {
            defaulted: item.defaultBool === 1,
            happenDate: item.happenDate ? moment(item.happenDate).format('YYYY-MM-DD') : '',
            files: item.fileUrl.split(','),
            manageCostId: obj.id
          }
        } else {
          return {
            applyType: null, // 报销类目
            happenDate: '', // 发生日期
            amount: 0, // 申请金额
            fileList: [],
            files: []
          }
        }
        // item.applyType =
        // item.amount = item.defaulted ? item.amt : 0
        // item.defaultAmt = item.amt
        // item.manageCostId = item.id
        // item.apv = item.apv
        // item.costMin = item.costMin
        // item.costMax = item.costMax
      } else {
        return {
          defaulted: item.defaultBool === 1,
          happenDate: item.happenDate ? moment(item.happenDate).format('YYYY-MM-DD') : '',
          files: item.fileUrl.split(',')
        }
      }
    },
    checkInList (item, list) {
      if (!this.checkDataExistsInList(item.applyType, list, 'applyType')) return false
      const find = list.find(e => e.applyType === item.applyType)
      if (!find) return false
      return find.visitVersion.indexOf(item.visitId) !== -1 && find.visitStages.indexOf(item.visitRecordId) !== -1
    },
    checkDataExistsInList (id, list, prop) {
      return list.some(e => e[prop] === id)
    },
    getFileList (record) {
      const { fileList, fileArr } = record
      if (fileList.length) return fileList

      const fileArrList = JSON.parse(fileArr)
      return fileArrList.map(item => {
        return {
          fileName: item.fileName,
          fileUrl: item.afterUrl || item.originalUrl
        }
      })

      /* const { fileList, fileArr } = record
      if (!fileArr) {
        return fileList
      }
      const fileArrList = JSON.parse(fileArr)
      return fileArrList.map(item => {
        return {
          fileName: item.fileName,
          fileUrl: item.afterUrl || item.originalUrl
        }
      }) */
    },
    clearList () {
      this.formList = []
    },
    // 申请类目切换
    applyTypeChange (val, row, i) {
      const feeList = row.feeList || this.mattersList
      const item = feeList.find(v => v.applyType === val)
      if (item.defaulted) this.formList[i].happenDate = null
      this.$set(this.formList[i], 'defaulted', item.defaulted === 1)
      this.formList[i].amount = item.defaulted ? item.amt : 0
      this.formList[i].defaultAmt = item.amt
      this.formList[i].manageCostId = item.id
      this.formList[i].apv = item.apv
      this.formList[i].costMin = item.costMin
      this.formList[i].costMax = item.costMax
    },
    // 打开文件上传弹窗
    // uploadFile (record, i) {
    //   this.uploadFileVisible = true
    //   this.currentTarget = record
    //   this.$refs.uploadFileRef.copyData(record)
    //   this.$refs.uploadFileRef.resetData()
    // },
    // 关闭文件上传
    // closeUpload (info) {
    //   const target = this.formList.find(item => item.uniqueId === info.uniqueId)
    //   if (target) {
    //     target.fileList = info.fileList
    //     if (target.fileList.length) {
    //       target.fileUrl = target.fileList.map(item => item.fileUrl).toString()
    //     } else {
    //       target.fileUrl = ''
    //     }
    //   }
    //   this.uploadFileVisible = false
    // },
    uploadFile (file) {
      this.fileList = file
      this.$emit('updateFee', this.formList, this.totalAmt, this.fileList)
    },
    fileChange (event, record, index) {
      const arr = []
      event.forEach(item => {
        let file = this.fileList.filter(e => e.fileUrl === item)[0]
        arr.push(file)
      })
      record.fileList = arr
      record.fileUrl = event.join(',')
    },
    // 访视列表下拉改变
    async handleVisitChange (value, node, record) {
      record.visitRecordId = value
      record.visitRecordInfo = node.data.attrs.name + ':' + node.data.attrs.stage
      const res = await visitStageByFeeCategory({
        versionId: this.versionId,
        visitStageId: value,
        ptsTypeId: this.ptsTypeId,
        proId: localStorage.getItem('CURRENT_PROID'),
        type: 2,
        researchId: this.researchId
      })
      res.forEach(i => {
        i.editable = false
        i.fileList = []
        i.amt = i.defaulted ? i.amt : ''
      })
      record.applyType = undefined
      this.$set(record, 'feeList', res)
    },
    // 保存、添加行
    async saveRow (row) {
      const target = this.formList.findIndex(item => item.uniqueId === row.uniqueId)
      this.saveTarget = target
      if (!this.formList[target].applyType || !this.formList[target].amount) {
        this.$message.error(this.$t('all.autotext207'))
        return
      }
      if (Number(this.formList[target].amount) === 0) {
        this.$message.error(this.$t('all.autotext704'))
        return
      }
      if (this.formList[target].costError) {
        return
      }
      if (parseInt(this.formList[target].apv) === 1) {
        // 受试者
        if (this.type !== 1 && !this.formList[target].fileUrl.length) {
          this.$message.error(this.$t('all.autotext328'))
          return false
        } else {
          // 研究者 判断上传还是补充
          if (this.formList[target].btnSwitch && !this.formList[target].supplyRemark) {
            this.$message.error(this.$t('all.autotext285'))
            return false
          } else if (!this.formList[target].fileUrl) {
            this.$message.error(this.$t('all.autotext328'))
            return false
          }
        }
      }
      // console.log(this.formList.findIndex(item => item.applyType === this.formList[target].applyType))
      // let _index = this.formList.findIndex(item => item.applyType === this.formList[target].applyType)
      // if (_index !== target) {
      //   this.commentVisible = true
      //   return
      // }
      // const res = await checkFeeCategoryForFeeApply({
      //   applyType: this.formList[target].applyType,
      //   proId: localStorage.getItem('CURRENT_PROID'),
      //   pstId: this.ptsId,
      //   researchDetailId: this.researchDetailId
      // })
      // if (res) {
      //   this.commentVisible = true
      // } else {
      //   this.sureOk()
      // }
      this.sureOk()
    },
    sureOk () {
      this.formList[this.saveTarget].isNew = false
      this.formList[this.saveTarget].editable = false
      this.$set(this.formList[this.saveTarget], 'comment', this.form.comment)
      this.calculateCost()
      this.$emit('updateFee', this.formList, this.totalAmt, this.fileList)
      this.saveTarget = ''
      this.commentVisible = false
      this.form.comment = ''
      this.$forceUpdate()
    },
    handleOk () {
      this.$refs.ruleForm.validate(valid => {
        if (!valid) return
        this.sureOk()
      })
    },
    // 计算费用
    calculateCost () {
      const arr = this.formList.filter(item => item.editable === false)
      this.totalAmt = 0
      if (arr.length > 0) {
        arr.forEach(item => {
          this.totalAmt += Number(item.amount)
        })
      }
    },
    // 上传、备注二选一
    onChange1 (record, e) {
      record.btnSwitch = !record.btnSwitch
      record.btnRemarks = !record.btnRemarks
      record.fileUrl = []
      record.fileName = []
      record.afterFileUrl = ''
      record.supplyRemark = ''
      record.supply = e.target.checked ? 1 : 0
      this.$forceUpdate()
    },
    // 新增行
    newMember () {
      this.formList.push({
        No: this.formList.length + 1, // No
        uniqueId: Math.random().toString().substr(2, 10), // 当前行的唯一标识
        isNew: true,
        apv: this.type === 2 ? 1 : null, // 是否审批
        applyType: null, // 报销类目
        amount: null, // 申请金额
        supplyRemark: '', // 补充说明
        editable: true, // 可修改
        manageCostId: null, // 报销类目id (费用科目接口返回的id)
        supply: 0, // 是否研究者/受试者补充资料  0:否  1:是   费用科目接口返回的apv字段决定，apv=1时开启图片上传功能
        btnSwitch: false, // 上传和补充资料二选一
        btnRemarks: false, // 上传和补充资料二选一
        fileUrl: '', // 资料地址
        afterFileUrl: '', // 脱敏后资料地址
        fileName: [], // 资料名字
        fileList: [],
        defaultAmt: null, // 默认金额
        loading: false,
        // 受试者
        happenDate: moment().format('YYYY-MM-DD'), // 发生日期
        visitRecordId: null, // 访视记录id 访视版本下的访视记录列表id
        visitRecordInfo: null // 访视名词  访视列表返回的name
      })
      this.$emit('updateFee', this.formList, this.totalAmt, this.fileList)
    },
    // 编辑当前行
    async toggle (record) {
      if (record.visitRecordId) {
        const res = await visitStageByFeeCategory({
          versionId: this.versionId,
          visitStageId: record.visitRecordId,
          ptsTypeId: this.ptsTypeId,
          proId: localStorage.getItem('CURRENT_PROID'),
          type: 2,
          researchId: this.researchId
        })
        res.forEach(i => {
          i.editable = false
          i.fileList = []
          i.amt = i.defaulted ? i.amt : ''
        })
        this.$set(record, 'feeList', res)
      }
      const target = this.formList.find(item => item.uniqueId === record.uniqueId)
      // 将No提取出来 因为No会动态变化
      const { No, ...targetCopy } = { ...target }
      // 因为fileName、fileUrl为数组 解构为浅拷贝 在上传文件成功后再取消操作仍会造成文件名push到fileName中,故需深拷贝
      target._originalData = JSON.parse(JSON.stringify(targetCopy))
      target.editable = !target.editable
      this.$forceUpdate()
    },
    // 取消保存当前行
    cancel (record) {
      const target = this.formList.find(item => item.uniqueId === record.uniqueId)
      // 将No提取出来 因为如果进行了删除操作，此时No已经动态变化
      const { No, ...targetCopy } = { ...target }
      Object.keys(targetCopy).forEach(item => {
        target[item] = target._originalData[item]
      })
      target._originalData = undefined
      this.$forceUpdate()
    },
    // 删除行
    remove (record) {
      const newData = this.formList.filter(item => item.uniqueId !== record.uniqueId)
      // 删除当前行后重新赋值整个表单的序列号
      for (let i = 0; i < newData.length; i++) {
        newData[i].No = i + 1
      }
      this.formList = newData
      this.calculateCost()
      this.$emit('updateFee', this.formList, this.totalAmt, this.fileList)
      this.$forceUpdate()
    },
    isAmountValid (record) {
      const price = Number(record.amount)
      let error = false
      if (record.amount) {
        if (record.costMin && record.costMax) {
          error = price < record.costMin || price > record.costMax
        } else if (record.costMin) {
          error = price < record.costMin
        } else if (record.costMax) {
          error = price > record.costMax
        }
      }
      return error
    },
    // 金额输入
    onAmountChange (record, e) {
      record.amount = this.$commonMethods.moneyCheck(e.target.value)
      this.$forceUpdate()
    }
  }
}
</script>

